package com.zqxq.lottery.controller.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.lottery.entity.o2o.user.UserAddressO2O;
import com.zqxq.lottery.entity.po.user.UserAddressPO;
import com.zqxq.lottery.entity.po.user.UserInfoPO;
import com.zqxq.lottery.entity.vo.user.UserAddressVO;
import com.zqxq.lottery.mapper.user.UserInfoMapper;
import com.zqxq.lottery.service.user.IUserAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


@RestController
@Slf4j
@RequestMapping("/address")
public class UserAddressController {

    @Autowired
    private IUserAddressService userAddressService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @PostMapping("/get")
    public Result getAddressById(@RequestParam("id") String id){
        Result rs = new Result();
        if(id == null || id==""){
            return new Result(CodeEnum.FAIL_100002.getCode(), CodeEnum.FAIL_100002.getMsg());
        }
        try{
            UserAddressPO userAddressPO = userAddressService.selectById(id);
            UserAddressVO userAddressVO = UserAddressO2O.toVO(userAddressPO);
            rs.setData(userAddressVO);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("User Address Get Error:",e);
        }
        return rs;
    }

    @PostMapping("/save")
    public Result saveAddress(@RequestBody UserAddressVO vo){
        Result rs = new Result();
        if(vo == null){
            return new Result(CodeEnum.FAIL_100002.getCode(), CodeEnum.FAIL_100002.getMsg());
        }
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("user_id",vo.getUserId());
        wrapper.setSqlSelect("id,user_id");
        Integer count = userAddressService.selectCount(wrapper);
        if(StringUtils.isEmpty(vo.getId()) && count>0){
            return new Result(CodeEnum.FAIL_100002.getCode(), "每个用户只有一个收货地址！");
        }
        try{
            UserAddressPO userAddressPO = UserAddressO2O.toPO(vo);
            userAddressService.insertOrUpdate(userAddressPO);
            UserAddressPO userAddressPO1 = userAddressService.selectOne(wrapper);
            UserInfoPO userInfoPO = new UserInfoPO();
            userInfoPO.setId(userAddressPO1.getUser_id());
            userInfoPO.setAddress_id(userAddressPO1.getId());
            userInfoMapper.updateById(userInfoPO);
            vo.setId(String.valueOf(userAddressPO1.getId()));
            rs.setData(vo);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("User Address Save Error:",e);
        }
        return rs;
    }

}
